package com.pine.dcts.exception;


import com.pine.dcts.common.DctsException;
import com.pine.dcts.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;

/**
 * @author xiaoyuan
 * @create 2019/8/22 12:30
 **/
@RestController
@Slf4j
public class RequestExceptionHandler implements ErrorController {
    @Value("${server.error.path:${error.path:/error}}")
    private String errorPath;
    @Value("${spring.profiles.active:dev}")
    public String activeProfile;
    private static final String FILE_UPLOAD_MAX_ERROR="上传文件已经超出最大限制";
    @Override
    public String getErrorPath() {
        return errorPath;
    }

    @RequestMapping(value = "${server.error.path:${error.path:/error}}")
    public Result errorPage(HttpServletRequest request) {
        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        Exception exception = (Exception) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
        log.error("系统错误：错误码是"+status,exception);
        if(exception instanceof DctsException){
            DctsException serviceException = (DctsException) exception;
            return Result.error(serviceException.getCode(), getMessage(exception,HttpStatus.getByValue(serviceException.getCode())));
        }
        if (status != null) {
            Integer code = Integer.valueOf(status.toString());
            HttpStatus httpStatus = HttpStatus.getByValue(code);
            if (httpStatus == null) {
                return Result.error(HttpStatus.UNKNOW_ERROR.value(), HttpStatus.UNKNOW_ERROR.getMessage());
            }
            return Result.error(httpStatus.value(), getMessage(exception,httpStatus));
        }
        return Result.error(HttpStatus.UNKNOW_ERROR.value(), HttpStatus.UNKNOW_ERROR.getMessage());
    }

    private String getMessage(Exception exception, HttpStatus status) {
        if(exception==null){
            return status.getMessage();
        }
        if(exception.getCause()!=null&&exception.getCause() instanceof MaxUploadSizeExceededException)
        {
            return FILE_UPLOAD_MAX_ERROR;
        }
        if(exception.getCause()!=null&&exception.getCause() instanceof DctsException)
        {
            return exception.getCause().getMessage();
        }
        return status.getMessage();

    }
}
